<?php

namespace app\common\service\face;

use app\util\rke\AioBase;
use app\model\AdminStaff as StaffModel;
use app\model\AdminSchoolDevice as AdminSchoolDeviceModel;
use think\facade\Log;

/**
 * 人脸机设备
 */
class FaceDevice extends AioBase
{
    /**
     * 异步开启指定的人脸机门禁
     * @param $serial 序列号
     * @param $operator 执行动作
     * @param $keepOpen 常开操作（0：关闭，1：开启）
     * @return bool
     */
    public static function openDoor($serial, $operator, $keepOpen)
    {
        if (!$serial || !$operator) {
            return false;
        }
        if ($operator == 'Unlock') {
            $sendData = [
                'operator' => 'Unlock',
                'messageId' => self::getMessageId(),
                'info' => [
                    'uid' => 0,
                    'openDoor' => '1',
                    'showInfo' => '请通行',
                ]
            ];
        }
        else if ($operator == 'SetKeepOpen') {
            $sendData = [
                'operator' => 'SetKeepOpen',
                'messageId' => self::getMessageId(),
                'info' => [
                    'KeepOpen' => $keepOpen
                ]
            ];
        }
        Log::error('发送远程开门指令 ');
        Log::error($sendData);
        return self::createPublish($serial, $sendData);
    }

    /**
     * 写入用户人脸信息(含新增或修改)
     * @param $userId
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function editPerson($userId)
    {
        // 填充学生数据
        $userInfo = StaffModel::field('id,school_id,name,sex,id_card,phone,face,smart_card')->where('id', $userId)->find();
        $domain = env('FACE_DEVICE.FD_DOMAIN', '');
        $sendData = [
            'messageId' => self::getMessageId(),
            'operator' => 'EditPerson',
            'info' => [
                "customId" => $userInfo['id'],
                "name" => $userInfo['name'],
                "nation" => 1,
                "gender" => $userInfo['name'] == '女' ? 1 : 0,
                "cardType" => 0,
                "idCard" => $userInfo['id_card'],
                "tempCardType" => 0,
                "telnum1" => $userInfo['phone'],
                "cardType2" => 2,
                'cardNum2' => $userInfo['id'],// 用用户ID做卡号 韦根门禁卡号
                'CardMode' => 1,
                "personType" => 0,
                "picURI" => $domain . $userInfo['face'],
                "RFCardMode" => 1,
                "RFIDCard" => strtoupper($userInfo['smart_card'] ?: '00000000')
            ]
        ];
        self::batchDevice($userInfo['school_id'], $sendData);
    }

    /**
     * 同步指定学校的所有人员数据
     * @param $school_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function batchAllPerson($school_id)
    {
        // 批量把学校的人员都添加进设备
        $nowTime = time();
        $domain = env('FACE_DEVICE.FD_DOMAIN', '');
        StaffModel::field('id,school_id,name,sex,id_card,phone,face,smart_card')->where([
            'school_id' => $school_id,
            'is_delete' => 0,
        ])->chunk(1000, function ($userList) use ($school_id, $nowTime, $domain) {
            $info = [];
            foreach ($userList as $value) {
                // 判断是否有人脸图像
                if (empty($value['face'])) {
                    continue;
                }
                // 判断毕业时间
                if (!empty($value['entrance_time']) && !empty($value['graduate_time'])) {
                    $value['entrance_time'] = strtotime($value['entrance_time']);
                    $value['graduate_time'] = strtotime($value['graduate_time']) + 2592000;
                    if ($nowTime < $value['entrance_time'] || $value['graduate_time'] < $nowTime) {
                        continue;
                    }
                }
                $info[] = [
                    "customId" => $value['id'],
                    "name" => $value['name'],
                    "nation" => 1,
                    "gender" => $value['name'] == '女' ? 1 : 0,
                    "cardType" => 0,
                    "idCard" => $value['id_card'],
                    "tempCardType" => 0,
                    "telnum1" => $value['phone'],
                    "cardType2" => 2,
                    'cardNum2' => $value['id'],// 用用户ID做卡号 韦根门禁卡号
                    'CardMode' => 1,
                    "personType" => 0,
                    "picURI" => $domain . $value['face'],
                    "RFCardMode" => 1,
                    "RFIDCard" => strtoupper($value['smart_card'] ?: '00000000')
                ];
            }
            $sendData = [
                'messageId' => self::getMessageId(),
                'DataBegin' => 'BeginFlag',
                'operator' => 'EditPersonsNew',
                'PersonNum' => count($info),
                'info' => $info,
                'DataEnd' => 'EndFlag'
            ];
            self::batchDevice($school_id, $sendData);
        }, 'id', 'asc');
    }

    /**
     * 删除单个人员信息
     * @param $school_id
     * @param $userId
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function delPerson($school_id, $userId)
    {
        $sendData = [
            'messageId' => self::getMessageId(),
            'operator' => 'DelPerson',
            'info' => [
                "customId" => $userId,
            ]
        ];
        self::batchDevice($school_id, $sendData);
    }

    /**
     * 删除所有人员信息
     * @param $school_id
     * @param $userId
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function delAllPerson($school_id)
    {
        $sendData = [
            'messageId' => self::getMessageId(),
            'operator' => 'DeleteAllPerson',
            'info' => [
                "deleteall" => 1,
            ]
        ];
        self::batchDevice($school_id, $sendData);
    }

    /**
     * 批量下发到各个人脸机
     * @param $school_id
     * @param $sendData
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private static function batchDevice($school_id, $sendData)
    {
        // 获取人脸设备所有信息
        $deviceList = AdminSchoolDeviceModel::getFaceBySchoolList($school_id);
        // 传输人脸信息
        foreach ($deviceList as $value) {
            Log::error('发送人脸机人员同步请求 school_id '.$school_id.' serial '.$value['serial']);
            Log::error($sendData);
            self::createPublish($value['serial'], $sendData);
        }
    }

    /**
     * 图片链接转base64
     * @param $file
     * @return string
     */
    private static function base64EncodeImage($file)
    {
        dump($file);
        if ($fp = fopen($file, "rb", 0)) {
            $gambar = fread($fp, filesize($file));
            fclose($fp);
            $base64 = chunk_split(base64_encode($gambar));
            // 输出
//            $encode = '<img src="data:image/jpg/png/gif;base64,' . $base64 .'" >';
            return $base64;
        }
        return '';
    }

    public static function base64_image_content($base64_image_content,$path, $filename){
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            if(!file_exists($path)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($path, 0777);
            }
            $new_file = $path.$filename;
            try {
                file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)));
                return true;
            } catch (\Exception $e) {
                \think\facade\Log::error('人脸保存失败：'.$e->getMessage());
                return false;
            }
        }
        return true;
    }
}